package haois.module.system.rest;

import haois.constant.Reply;
import haois.constant.ReturnState;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


/**
 * Created by RuiHaoZ on 2018/4/28 23:45
 */
@RestController
@RequestMapping("/api/web/email")
public class EmailController {
    private String authUserName = "haoofwell@126.com";
    private String authPassword = "thinK0java";
    private String hostName = "SMTP.126.com";
    private String fromEmail = authUserName;
    private String fromName = "RuiHaoZ";

    @RequestMapping(value = "/send", method = RequestMethod.POST, params = {"toUser","title"})
    public String sendEmail(String toUser, String title, String content) {
        try {
            SimpleEmail email = new SimpleEmail();
            // 必须放在前面，否则乱码
            email.setCharset("UTF-8");
            email.setHostName(hostName);
            //邮件服务器验证：用户名/密码
            email.setAuthentication(authUserName, authPassword);
            // 设置发送人邮箱和名字
            email.setFrom(fromEmail, fromName);
            // 设置发送主题
            email.setSubject(title);
            email.setMsg(content);

            String[] tos = toUser.split(";");
            for (int i = 0; i < tos.length; i++) {
                // 设置收件人可以是多个
                email.addTo(tos[i]);
            }
//            msgInfo.append("\r\n\t");
            String sendReply = email.send();
            return new Reply(ReturnState.CODE_00, sendReply).toJson();
        } catch (EmailException e) {
            return new Reply(ReturnState.CODE_10, e.getMessage()).toJson();
        } catch (Exception e) {
            return new Reply(ReturnState.CODE_10, e.getMessage()).toJson();
        }
    }

}
